<template>
  <view class="lamps">
    <div class="filter-box">
      <div class="filter-item" :class="{ active: currentFilter === LAMP_SET_TYPE.ALL }" @click="toggleFilter(LAMP_SET_TYPE.ALL)">
        所有灯具
      </div>
      <div class="filter-item" :class="{ active: currentFilter === LAMP_SET_TYPE.SINGLE }" @click="toggleFilter(LAMP_SET_TYPE.SINGLE)">
        单独设置灯具
      </div>
      <div class="filter-item" :class="{ active: currentFilter === LAMP_SET_TYPE.GROUP }" @click="toggleFilter(LAMP_SET_TYPE.GROUP)">
        分组设置灯具
      </div>
    </div>
    <view class="section-content">
      <view v-show="!lampList.length" class="no-content">
        暂无数据
      </view>
      <view class="lamp-box">
        <view
            v-for="item in lampList"
            :key="item.id"
            :id="item.id"
            class="lamp-item"
            :class="{ 'offline': !item.o, active: targetSelectLampId === item.id }"
            @click="showLampSetDialog(item)">
          <image class="lamp-icon" src="@/static/image/icon-lamp.png"></image>
          <view v-show="labelMap[item.c]" class="lamp-label" :class="item.c">
            <view class="label-text">{{ labelMap[item.c] }}</view>
          </view>
          <view class="lamp-content">
            <view class="line lamp-name">{{ lampNameMap[item.id] }}</view>
            <view class="line lamp-info">{{ lampInfoMap[item.id] }}</view>
          </view>
        </view>
      </view>
    </view>
    <uni-popup
        ref="lampSetDialog"
        type="center">
      <view class="set-box">
        <view class="title">
          设置灯具
        </view>
        <view class="form">
          <view class="line">
            <view class="label">灯具名称</view>
            <view class="content">
              <uni-easyinput :disabled="lampSetDialog.loading" trim="all" :clearable="false" maxlength="20" v-model="lampSetDialog.form.name" placeholder="请输入灯具名称"></uni-easyinput>
            </view>
          </view>
          <view class="line">
            <view class="label">单灯设置</view>
            <view class="content">
              <switch :checked="lampSetDialog.form.enableSingle" @change="switchSingleControl" />
            </view>
          </view>
          <view v-if="lampSetDialog.form.enableSingle" class="line">
            <view class="label">选择场景</view>
            <view class="content">
              <uni-data-select
                  :disabled="lampSetDialog.loading"
                  v-model="lampSetDialog.form.sceneCode"
                  :localdata="sceneList"
                  :clear="false"
              ></uni-data-select>
            </view>
          </view>
        </view>
        <view class="btn-box">
          <view class="btn" @click="closeLampSet">取消</view>
          <view class="btn submit" @click="confirmLamp()">确定</view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import {fixedDecimal} from '@/utils';

const LAMP_SET_TYPE = {
  ALL: 'all',
  SINGLE: 'single',
  GROUP: 'group',
};
export default {
  props: {
    projectInfo: {
      type: Object
    }
  },
  data() {
    return {
      LAMP_SET_TYPE,
      isPageShow: false,
      errorCount: 0,
      maxErrorCount: 10,
      requestTask: null,
      sceneList: [],
      currentFilter: LAMP_SET_TYPE.ALL,
      lampList: [],
      lampNameMap: {},
      lampInfoMap: {},
      labelMap: {
        s: '单设',
        g: '分组'
      },
      allLampList: [],
      singleSetLampList: [],
      groupSetLampList: [],
      lampMap: {},
      targetSelectLampId: '',
      targetSelectLamp: null,
      timeoutIndex: 0,
      getSelectLampErrorCount: 0,
      startScan: true,
      lampSetDialog: {
        target: null,
        loading: false,
        form: {
          name: '',
          enableSingle: false,
          sceneCode: '',
        },
      },
    }
  },
  computed: {
    canEdit() {
      return this.projectInfo.canEdit
    }
  },
  watch: {
    projectInfo() {
      this.initData()
    }
  },
  beforeDestroy() {
    this.abortLongRequest();
    this.startScan = false
  },
  mounted() {
    this.initData()
  },
  methods: {
    initData() {
      if (this.projectInfo?.id) {
        this.getLampList()
        this.getProjectScenario()
      }
    },
    getProjectScenario() {
      const self = this
      uni.request({
        url: '/project_scene/list',
        data: {
          xm_id: self.projectInfo.id
        },
        noLoading: true,
        success(result) {
          if (result.data.success && Array.isArray(result.data.data)) {
            const arr = []
            result.data.data.forEach(item => {
              const sceneItem = {
                key: item.id,
                value: item.id,
                text: item.name || '',
              }
              arr.push(sceneItem)
            })
            self.sceneList = arr
          }
        }
      })
    },
    getLampList() {
      const self = this
      uni.request({
        url: '/project/getnodes',
        data: {
          xm_id: self.projectInfo.id,
        },
        success(result) {
          if (result.data.success && Array.isArray(result.data.data)) {
            self.allLampList = []
            self.singleSetLampList = []
            self.groupSetLampList = []
            self.lampNameMap = {}
            self.lampMap = {}
            self.lampList = []
            result.data.data.sort((left, right) => right.light - left.light);
            result.data.data.forEach((item) => {
              self.processLampItem(item, self);
            });
            self.lampList = self.allLampList
          }
        }
      })
    },
    processLampItem(item, self) {
      const checkTimeInterval = (parseInt(self.projectInfo.warning_hours) || 120) * 3600;
      item.name = item.name || `灯具${item.id}`;
      item.light = parseFloat(item.light) || 0;
      item.isOnline = item.past < checkTimeInterval;
      item.infoText = fixedDecimal(item.light, 2);
      item.labelText = '';
      item.labelStyle = '';
      item.enableSingle = false;
      item.setType = LAMP_SET_TYPE.ALL;
      // 小程序一个对象大小需要小于一定长度，否则会报错，这里简化数据
      const lampData = {
        id: item.id,
        o: +item.isOnline
      };
      self.lampNameMap[lampData.id] = item.name
      self.lampInfoMap[lampData.id] = item.infoText
      self.lampMap[item.id] = lampData
      if (item.scene) {
        lampData.s = item.scene
      }
      if (item.gnum === 254) {
        lampData.eS = 1;
        lampData.c = 's';
        self.singleSetLampList.push(lampData);
      } else if (item.gnum !== 0) {
        lampData.c = 'g';
        self.groupSetLampList.push(lampData);
      }
      self.allLampList.push(lampData);
    },
    toggleFilter(type) {
      if (this.currentFilter === type) return;
      this.currentFilter = type;
      switch (type) {
        case LAMP_SET_TYPE.ALL:
          this.lampList = this.allLampList;
          break;
        case LAMP_SET_TYPE.SINGLE:
          this.lampList = this.singleSetLampList;
          break;
        case LAMP_SET_TYPE.GROUP:
          this.lampList = this.groupSetLampList;
          break;
      }
    },
    getSelectLamps() {
      const self = this
      if (!self.startScan) return
      self.abortLongRequest()
      self.requestTask = uni.request({
        url: '/gw/cmd2',
        data: {
          cmd: 'get_sel_node',
          uid: self.projectInfo.gateway_id
        },
        noLoading: true,
        success(result) {
          self.errorCount = 0
          if (result.data?.success) {
            if (!result.data.data?.uid) return;
            self.targetSelectLampId = result.data.data.uid;
            if (self.targetSelectLampId && !self.lampMap[self.targetSelectLampId]) {
              const likeLamp = {
                id: self.targetSelectLampId,
                gnum: 0,
                past: 0,
              };
              self.processLampItem(likeLamp, self);
            }

            self.$nextTick(() => {
              self.targetSelectLamp = self.lampMap[self.targetSelectLampId];
              const scrollTop = 210 + Math.floor(self.targetSelectLamp.index / 3) * 51
              wx.pageScrollTo({
                scrollTop
              })
            });
          }
        },
        fail() {
          self.errorCount += 1
        },
        complete(result) {
          if (result.errMsg?.includes('abort')) return
          if (result.statusCode !== 200) {
            self.errorCount += 1
          }
          if (self.errorCount >= self.maxErrorCount) {
            uni.showToast({
              icon: 'error',
              title: '获取灯具失败'
            })
            return
          }
          setTimeout(self.getSelectLamps, 100)
        }
      })
    },
    abortLongRequest() {
      const self = this
      if (self.requestTask && self.requestTask.abort) {
        self.requestTask.abort()
        self.requestTask = null
      }
    },

    showLampSetDialog(target) {
      const self = this
      if (!self.projectInfo.canEdit) return;
      self.lampSetDialog.target = target;
      self.lampSetDialog.form.name = self.lampNameMap[target.id];
      self.lampSetDialog.form.enableSingle = !!target.eS;
      self.lampSetDialog.form.sceneCode = target.s || '';
      self.$refs.lampSetDialog.open()
    },
    closeLampSet() {
      const self = this
      self.$refs.lampSetDialog.close()
    },
    switchSingleControl() {
      const self = this
      self.lampSetDialog.form.enableSingle = !self.lampSetDialog.form.enableSingle
    },
    confirmLamp() {
      const self = this
      const { loading, target, form } = self.lampSetDialog;
      if (!target || loading) return;
      if (form.enableSingle && !form.sceneCode) {
        uni.showToast({
          title: '请选择场景',
          icon: 'none',
          duration: 3000
        })
        return
      }
      self.lampSetDialog.loading = true;
      self.closeLampSet()
      const promiseList = []
      if (target.enableSingle !== form.enableSingle) {
        if (target.enableSingle) {
          promiseList.push(self.deleteSingle());
        }
      }
      if (form.enableSingle) {
        promiseList.push(self.setSingle());
      }
      Promise.all(promiseList).then(() => {
        self.lampSetDialog.loading = false;
        uni.showToast({
          title: '设置成功',
          icon: 'success',
          duration: 2000
        })
        self.getLampList();
      })
    },
    setSingle() {
      const self = this
      return new Promise((resolve) => {
        uni.request({
          url: '/project/set_node',
          data: {
            id: self.projectInfo.id,
            uid: self.lampSetDialog.target.id,
            name: self.lampSetDialog.form.name,
            scene: self.lampSetDialog.form.sceneCode,
          },
          complete() {
            resolve()
          }
        });
      })
    },
    deleteSingle() {
      const self = this
      return new Promise((resolve) => {
        uni.request({
          url: '/project/del_node',
          data: {
            id: self.projectInfo.id,
            uid: self.lampSetDialog.target.id,
          },
          complete() {
            resolve()
          }
        })
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.lamps {
  padding: 30rpx;
  border-radius: 10rpx;
  background-color: $white;
  min-height: 50vh;
}
.filter-box {
  display: flex;
  gap: 16rpx;
  font-size: 20rpx;
  .filter-item {
    text-align: center;
    padding: 16rpx 16rpx;
    border-radius: 10rpx;
    background-color: $background-info;
    color: $text-main;
    cursor: pointer;
    .count {
      text-align: center;
    }
    &.active {
      background-color: $primary;
      color: #fff;
      cursor: default;
    }
  }
}
.section-content {
  margin-top: 20rpx;
}
.lamp-box {
  display: grid;
  grid-template-columns: repeat(3, 200rpx);
  grid-gap: 16rpx;
}
.lamp-item {
  height: 86rpx;
  position: relative;
  padding: 14rpx 34rpx 12rpx 48rpx;
  font-size: 20rpx;
  border: 2rpx solid $border-base;
  border-radius: 10rpx;
  &.offline {
    background-color: $background-dark;
    .lamp-icon {
      filter: grayscale(90%);
    }
    .lamp-info {
      color: $text-secondary;
    }
  }
  &.active {
    background-color: rgba($warning, .3);
    .lamp-name {
      color: $primary;
    }
  }
}
.lamp-icon {
  position: absolute;
  left: 10rpx;
  top: 18rpx;
  width: 31rpx;
  height: 47rpx;
}
.lamp-label {
  position: absolute;
  right: -2rpx;
  top: -2rpx;
  bottom: -2rpx;
  width: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-top-right-radius: 10rpx;
  border-bottom-right-radius: 10rpx;
  &.g {
    background-color: $warning;
  }
  &.s {
    background-color: $primary;
  }
  .label-text {
    position: relative;
    z-index: 2;
    font-size: 20rpx;
    color: #fff;
    text-align: center;
  }
}
.lamp-name {
  color: $text-secondary;
}
.lamp-info {
  margin-top: 4rpx;
  color: $text-main;
}
.set-box {
  background-color: #fff;
  border-radius: 10px;
  padding: 30rpx;
  width: 560rpx;
  font-size: 26rpx;
  .title {
    font-size: 32rpx;
    font-weight: bold;
  }
  .line {
    margin-top: 30rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .label {
      color: $text-secondary;
    }
    .content {
      width: 300rpx;
    }
  }
  .btn-box {
    margin-top: 30px;
    display: flex;
    align-items: center;
    .btn {
      height: 50rpx;
      flex: 1;
      text-align: center;
      color: $text-secondary;
      &.submit {
        color: $primary;
      }
    }
  }
}
.no-content {
  margin-top: 20vh;
  text-align: center;
  color: $text-secondary;
}
</style>
